package main

import (
	"errors"
	pb "gitee.com/JaneCrysteal/grpcdemo/services"
	"net"
	"net/http"
	"net/rpc"
)

// GoodsServiceImpl
type GoodsServiceImpl struct {
}

// NewGoodsService --
func NewGoodsService() *GoodsServiceImpl{
	return new(GoodsServiceImpl)
}

// GetGoodsInfo --
func (that *GoodsServiceImpl) GetGoodsInfo(req pb.GetGoodsReq, result *pb.GoodsDataInfo) error {
	goodsInfoMap := map[int64]pb.GoodsDataInfo{
		1000: pb.GoodsDataInfo{Oid: 1000, Name: "五指毛桃"},
		1001: pb.GoodsDataInfo{Oid: 1001, Name: "黑布林"},
		1003: pb.GoodsDataInfo{Oid: 1003, Name: "三华李"},
	}

	resultResponse := goodsInfoMap[req.Oid]

	if "" == resultResponse.Name {
		return errors.New("商品信息不存在")
	}

	*result = goodsInfoMap[req.Oid]

	//fmt.Println("商品编号:", result.Oid, "商品名称:", result.Name)

	return nil
}

// main --
func main() {
	var err error

	// 注册方法
	err = rpc.RegisterName("goodsService",  NewGoodsService()) //rpc.Register(goodsService)
	if nil != err {
		panic(err.Error())
		return
	}

	// 注册http服务器,将RPC消息发送到默认的DefaultServer
	rpc.HandleHTTP()

	// 监听端口
	var listener net.Listener
	listener, err = net.Listen("tcp", ":8090")
	if nil != err {
		panic(err.Error())
		return
	}

	// 接待
	http.Serve(listener, nil)
}
